
import { defineStore } from 'pinia'
import { MD5 } from '@/utils/md5'
import { storage } from '@/utils/storage'
import { CATEGORIES_STORE } from '@/enum';
const useCateStore = defineStore('cate', {
    state: () => ({
        cateList: []
    }),
    getters: {

    },
    actions: {
        onLoadCateList() {
            this.getCateListFromDb()
        },
        createCate(cate) {
            cate.id = MD5(cate.name);
            storage.set({ [CATEGORIES_STORE]: [...this.cateList, cate] }, () => {
                console.log('Cate list saved to storage');
            }).then(() => {
                this.refreshCateList()
            })
        },
        deleteCate(id) {
            this.cateList = this.cateList.filter(item => item.id !== id)
            storage.set({ [CATEGORIES_STORE]: this.cateList }, () => {
                console.log('Cate list saved to storage');
            }).then(() => {
                this.refreshCateList()
            })
        },
        // 刷新
        refreshCateList() {
            this.getCateListFromDb()
        },
        getCateListFromDb() {
            storage.get([CATEGORIES_STORE], (result) => {
                console.log("result", result);
                if (result[CATEGORIES_STORE]) {
                    this.cateList = result[CATEGORIES_STORE];
                } else {
                    this.cateList = [];
                }
            });
        }
    },

})

export default useCateStore;